<?php

/**
 * This is the model class for table "{{goods_bm}}".
 * 
 * front_create
 * front_update
 * 
 *
 *
 * 
 * 
 * 
 * 
 *
 * The followings are the available columns in table '{{goods_bm}}':
 * @property string $GoodsBmID
 * @property string $City
 * @property string $CreditScore
 * @property string $DetailUrl
 * @property string $Image
 * @property integer $ItemType
 * @property string $Location
 * @property string $Nick
 * @property string $Pprice
 * @property string $ProductID
 * @property string $PromoPrice
 * @property string $Province
 * @property string $Sales
 * @property string $AddTime
 * @property integer $Status
 * @property string $UpdateTime
 * @property string $Sorting
 * @property string $UserID
 * @property string $UserName
 * @property string $AdminID
 * @property string $Money
 * @property string $CatID
 * @property string $StartTime
 * @property string $EndTime
 * @property string $SpecialID
 * @property string $StartSales
 * @property string $PlanSale
 * Excuse
 */
class GoodsBmModel extends BaseModel
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{goods_bm}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		//前台 新增的时候的验证   与  修改时候的验证
		//新增  有些
		//后台 不用考虑其它的，怎么样都可以
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		// 除了required是用户填写的之外，其它的一些都是通过淘宝API我们获取的。
		return array(
			array('DetailUrl', 'required', 'on' => 'front_create'),//前台新增的时候一定要填写链接，当修改的时候这是固定不变化的了,不能修改
			//array('PlanSale', 'required', 'on' => 'front_create,front_update'),//前台新增跟修改的时候都需要填写预计
			array('GoodsName, Image, CatID', 'required'),//任何情况都不能为空
			array('GoodsName', 'checkBaoming','on' => 'front_create,front_update'),//前台新增,修改的时候,注意的情况
			array('PlanSale, CatID', 'numerical', 'integerOnly'=>true),
			array('PromoPrice', 'numerical'),
			array('Excuse', 'checkStatus', 'on' => 'admin'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('Brief', 'safe'),
			array('City, CreditScore, DetailUrl, Image, ItemType, Location, Nick, Pprice, ProductID, PromoPrice, Province, Sales, AddTime, Status, UpdateTime, Sorting, UserID, UserName, AdminID, Money,CatID, StartTime, EndTime, SpecialID, StartSales, PlanSale, Excuse, IsMail,CountStartSales,CountSales,IsFreeShipping', 'safe', 'on'=>'admin'),
			array('GoodsBmID, City, CreditScore, DetailUrl, Image, ItemType, Location, Nick, Pprice, ProductID, PromoPrice, Province, Sales, AddTime, Status, UpdateTime, Sorting, UserID, UserName, AdminID, Money,CatID, StartTime, EndTime, SpecialID, StartSales, PlanSale, Excuse, IsMail,IsFreeShipping', 'safe', 'on'=>'search'),
		);
	}

	public function checkStatus(){
		if($this->Status == 2){
			if(empty($this->Excuse)){
				$this->addError('', '拒绝通过请填写理由');
				return false;
			}
		}
		return true;
	}

	public function checkBaoming(){

		if(empty($_POST['agree'])){
			$this->addError('', '你未同意');
			return false;
		}



		if(!yii::app()->user->isLogin()){
			$this->addError('', '你还未登录');
			return false;
		}
/*		if(yii::app()->user->Type != 1){
			$this->addError('', '只有商家才可以报名');
			return false;
		}*/

		//前台报名时的验证
		if($this->isNewRecord){
			$config = ConfigModel::getConfig();
			//这里再次的去访问淘宝API去获取一些信息过来，
			$arrData = TaobaoApi::getDataUrl($this->DetailUrl);
			if(!empty($arrData)){
				//添加的时候修改的字段
				$this->City = $arrData['city'];	
				$this->CreditScore = $arrData['credit_score'];	
				$this->ItemType = $arrData['item_type'];	
				$this->Location = $arrData['location'];	
				$this->Nick = $arrData['nick'];	
				$this->Pprice = $arrData['p_price'];	
				$this->ProductID = $arrData['product_id'];	
				$this->Province = $arrData['province'];		
				$this->Sales = $arrData['sales'];
				//当是C店的时候的检测
				if($this->ItemType == 0){
					if($this->Sales < $config['lowsales']){
						$this->addError('', "销量低于{$config['lowsales']}不能报名");
						return false;
					}
	                if ($this->CreditScore < $config['lowgrade']) {
	                    $this->addError('', '店铺等级不复合要求，最低需要店铺'.$config['lowgrade'].'级才可以报名！');
						return false;
	                }						
				}							
			}else{
				$this->addError('', '找不到记录');
				return false;
			}
			//找出最近的一条记录
			$model = GoodsBmModel::model()->find(BaseModel::getC(array('ProductID' => $this->ProductID, 'order' => 'GoodsBmID DESC')));
			if($model){
				if(in_array($model->Status, array(0,3))){
					$this->addError('', '该商品还在审核中，请耐心等待审核结果！');
					return false;
				}
				//审核通过的
				if($model->Status == 1){
					if(TIME_TIME < $model->EndTime){
						$this->addError('', '该商品正在热卖中');
						return false;
					}else{
						if(TIME_TIME < $model->EndTime + 86400*$config['baoming_ok']){
		                    $pre_end_time = date('Y-m-d H:i:s', $model->StartTime);
                            $pre_start_time = date('Y-m-d H:i:s', $model->EndTime);					
							$this->addError('', '对不起，宝贝“' . $model->ProductID . '”在' . $pre_start_time . '至' . $pre_end_time . '上过活动，活动结束' . $config['baoming_ok'] . '天之后才能重新报名。');
							return false;							
						}
					}
				}
				//审核通过的
				if($model->Status == 2){					
					if(TIME_TIME < ($model->AddTime + $config['baoming_ok']*84600)){
	                    $bm_no_time = date('Y-m-d H:i:s', $model->UpdateTime);
	                    $bm_time = date('Y-m-d H:i:s', $model->AddTime);
	                    $H = $config['baoming_no'] * 24;						
						$this->addError('', '宝贝“' . $model->ProductID . '”在' . $bm_time . '已报名，并于' . $bm_no_time . '审核不通过，审核不通过的宝贝，在' . $H . '小时之后才能重新报名。');
						return false;
					}
				}
			}
		}else{
			if(!($this->Status == 0 && $this->AdminID == 0)){
				$this->addError('', '商品正在审核或已取消报名,不能修改');
				return false;				
			}
		}
		return true;
	}


	public function beforeSave(){
		//前台人员不能修改的字段
		if(GROUP_NAME !== 'admin'){
			$this->AdminID = 0;
			$this->IsPay = 0;
			//用户需要付的钱  用户初始销量 * 产品价格 * 折扣 /100
			//$this->Money = $this->PlanSale * $this->Pprice * yii::app()->params->Discount / 100;

			//总共花的钱
			//$this->Money = $this->ServiceFee + $this->MoneyBond;

			//今天报名，然后从明天的10点开始,
			//上架的时间是三天
			$this->StartTime = strtotime('+1 day') + 36000;
			$this->EndTime = $this->StartTime + 3*86400;
			//新增时，，前台添加时
			if($this->isNewRecord){
				$this->Status = 0;
				$this->AddTime = TIME_TIME;
				$this->UserID = yii::app()->user->id;
				$this->UserName = yii::app()->user->UserName;
				//刚开始的时候初始销量等于获取的销量
				$this->StartSales = $this->Sales;
			}else{
				if(!($this->Status == 0 || $this->Status == 4)){
					$this->Status = 4;
				}
			}
		}else{

			if(!is_numeric($this->StartTime)){
				$this->StartTime = strtotime(date('Y-m-d 9:00:00', strtotime($this->StartTime)));
			}

			if(!is_numeric($this->EndTime)){
				$this->EndTime = strtotime(date('Y-m-d 9:00:00', strtotime($this->EndTime)));
			}	

			//是否修改了admin???如果状态有改变的话
			$objModel = self::model()->findByPk($this->GoodsBmID);
			if($this->Status != $objModel->Status){
				//当商品状态发生变化的时候给其发送短信或者邮件，
				//发送信息
				$user = MemberModel::getOneDataForUserID($this->UserID);
		        $data = array(
		            'GoodsBmID' => $this->GoodsBmID,
		            'ProductID' => $this->ProductID,
		            'Image' => $this->Image,
		            'GoodsName' => $this->GoodsName,
		            'Status' => $this->Status,
		            'AddTime' => $this->AddTime,
		            'StartTime' => $this->StartTime,
		            'EndTime' => $this->EndTime,
		            'AdminID' => $this->AdminID,
		            'UserID' => $this->UserID,
		            'Excuse' => $this->Excuse,
		            'Phone' => $user['Phone'],
		            'Email' => $user['Email'],
		        );
		        //调试模式关闭
		        if (defined('YII_DEBUG') && YII_DEBUG == false) {
		            //短信息与邮件通知
		            RedisCluster::getInstance()->push('snsNotice', $data);
		        }
				
				GoodsOperationModel::saveData($objModel, $this);
			}				
		}

		if($this->isNewRecord){
			$this->Zhekou = $this->Pprice/$this->PromoPrice;
		}	
		$this->Brief = CHtml::encode($this->Brief);
		return true;
	}


	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'GoodsBmID' => '报名ID',
			'GoodsName' => '商品名',
			'City' => '商家商城',
			'CreditScore' => '商家店铺等级',
			'DetailUrl' => '链接',
			'Image' => '图片',
			'ItemType' => '店铺的类型0C店 1为天猫',
			'Location' => '商家省市',
			'Nick' => '商家旺旺号',
			'Pprice' => '原价',
			'ProductID' => '商品ID',
			'PromoPrice' => '折扣价',
			'Province' => '省份',
			'Sales' => '销量',
			'AddTime' => '添加时间',
			'Status' => '审核状态',
			'UpdateTime' => '最后一次状态修改时间',
			'Sorting' => '排序',
			'UserID' => '商家ID',
			'UserName' => '商家用户名',
			'AdminID' => '后台审核ID',
			'Money' => '报名花的钱',
			'CatID' => '分类',
			'StartTime' => '上架时间',
			'EndTime' => '下架时间',
			'SpecialID' => '专场ID',
			'StartSales' => '初始销量',
			'Excuse' => '不通过原因',
			'IsPay' => '是否付款',
			'IsMail' => '是否是邮寄样品',
			'CountStartSales' => '自己统计的初始销量',
			'CountSales' => '目前自己统计的销量',
			'IsFreeShipping' => '是否免运费',
			'Brief' => '简介',
			'PlanSale' => '计划销量',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('GoodsBmID',$this->GoodsBmID,true);
		$criteria->compare('GoodsName',$this->GoodsName,true);
		$criteria->compare('City',$this->City,true);
		$criteria->compare('CreditScore',$this->CreditScore,true);
		$criteria->compare('DetailUrl',$this->DetailUrl,true);
		$criteria->compare('Image',$this->Image,true);
		$criteria->compare('ItemType',$this->ItemType);
		$criteria->compare('Location',$this->Location,true);
		$criteria->compare('Nick',$this->Nick,true);
		$criteria->compare('Pprice',$this->Pprice,true);
		$criteria->compare('ProductID',$this->ProductID,true);
		$criteria->compare('PromoPrice',$this->PromoPrice,true);
		$criteria->compare('Province',$this->Province,true);
		$criteria->compare('Sales',$this->Sales,true);
		$criteria->compare('AddTime',$this->AddTime,true);
		$criteria->compare('Status',$this->Status);
		$criteria->compare('UpdateTime',$this->UpdateTime,true);
		$criteria->compare('Sorting',$this->Sorting,true);
		$criteria->compare('UserID',$this->UserID,true);
		$criteria->compare('UserName',$this->UserName,true);
		$criteria->compare('AdminID',$this->AdminID,true);
		$criteria->compare('Money',$this->Money,true);
		$criteria->compare('CatID',$this->CatID,true);
		$criteria->compare('StartTime',$this->StartTime,true);
		$criteria->compare('EndTime',$this->EndTime,true);
		$criteria->compare('SpecialID',$this->SpecialID,true);
		$criteria->compare('StartSales',$this->StartSales,true);
		$criteria->compare('PlanSale',$this->PlanSale,true);
		$criteria->compare('IsMail',$this->IsMail);
		$criteria->compare('Excuse',$this->Excuse);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function createSearchCriteria(){
		$criteria=new CDbCriteria;

		$criteria->compare('GoodsBmID',$this->GoodsBmID,true);
		$criteria->compare('GoodsName',$this->GoodsName,true);
		$criteria->compare('City',$this->City,true);
		$criteria->compare('CreditScore',$this->CreditScore,true);
		$criteria->compare('DetailUrl',$this->DetailUrl,true);
		$criteria->compare('Image',$this->Image,true);
		$criteria->compare('ItemType',$this->ItemType);
		$criteria->compare('Location',$this->Location,true);
		$criteria->compare('Nick',$this->Nick,true);
		$criteria->compare('Pprice',$this->Pprice,true);
		$criteria->compare('ProductID',$this->ProductID,true);
		$criteria->compare('PromoPrice',$this->PromoPrice,true);
		$criteria->compare('Province',$this->Province,true);
		$criteria->compare('Sales',$this->Sales,true);
		$criteria->compare('IsMail',$this->IsMail);
		$criteria->compare('Excuse',$this->Excuse);


		if(!empty($_GET['add_start_time'])){
			$add_start_time = strtotime($_GET['add_start_time']);
			$criteria->addCondition('AddTime >= ' . $add_start_time);
		}
		if(!empty($_GET['add_end_time'])){
			$add_end_time = strtotime($_GET['add_end_time']) + 86400;
			$criteria->addCondition('AddTime <= ' . $add_end_time);
		}


		if(is_numeric($this->StartTime)){
			$criteria->compare('StartTime',$this->StartTime,true);
		}else{
			if(!empty($this->StartTime)){
				$StartTime = strtotime($this->StartTime);
				$criteria->addCondition('StartTime >= ' . $StartTime);	
			}		
		}

		if(is_numeric($this->EndTime)){
			$criteria->compare('EndTime',$this->EndTime);
		}else{
			if(!empty($this->EndTime)){
				$EndTime = strtotime($this->EndTime) + 86400;
				$criteria->addCondition('EndTime <= ' . $EndTime);
			}			
		}
		

		$criteria->compare('AddTime',$this->AddTime);
		$criteria->compare('Status',$this->Status);
		$criteria->compare('UpdateTime',$this->UpdateTime);
		$criteria->compare('Sorting',$this->Sorting);
		$criteria->compare('UserID',$this->UserID);
		$criteria->compare('UserName',$this->UserName,true);
		$criteria->compare('AdminID',$this->AdminID);
		$criteria->compare('Money',$this->Money,true);
		$criteria->compare('CatID',$this->CatID,true);

		$criteria->compare('SpecialID',$this->SpecialID,true);
		$criteria->compare('StartSales',$this->StartSales,true);
		$criteria->compare('PlanSale',$this->PlanSale,true);
		return 	$criteria;	
	}







	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return GoodsBmModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * 状态
	 * @return [type] [description]
	 */
	public static function getStatusHtml($mixData = false){
		$arrData = array(
			0 => '未审核/正在审核',
			1 => '审核通过',
			2 => '审核不通过',
			3 => '需要邮寄样品',
			4 => '用户已取消',		
			//5 => '下架',		这个模型里面可以不需要显示这个状态				
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}

	/**
	 * 店铺类型
	 * @return [type] [description]
	 */
	public static function getItemTypeHtml($mixData = false){
		$arrData = array(
			0 => '淘宝店',
			1 => '天猫店',
			2 => '天猫精品',			
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}


	/**
	 * 状态 ,,,前后台都用这个
	 * @return [type] [description]
	 */
	public  function getStatusOperationHtml(){
        $strResult = '';
        if($this->Status == 0){    //状态为0的操作
        	if($this->AdminID == 0){
        		$strResult .= '未审核';   /*adminid为0 */   		
        	}else{
        		if(GROUP_NAME == 'admin'){   //前后台的展示
        			$strResult .= '<font color="#0033FF">' . AdminUser::model()->getByUidFindName($this->AdminID) . '</font>' . '正在审核中';
        		}else{
        			$strResult .= '正在审核';
        		}
        	}
        }else if($this->Status == 1){
        	//审核通过
        	$strResult .= '审核通过';
        }else if($this->Status == 2){
        	//审核通过
        	$strResult .= '审核不通过';
        }else if($this->Status == 3){  //要让它邮寄样品
        	$strResult .= '邮寄样品';        	
        }else if($this->Status == 4){  //要让它邮寄样品
        	$strResult .= '用户取消';        	
        }else if($this->Status == 5){  //要让它邮寄样品
        	$strResult .= '手动下架';        	
        }

        if($this->IsPay == 0){
        	//$strResult .= '</br><font color="#FF0000">未付款</font>';
        }else if($this->IsPay == 1){
        	$strResult .= '</br><font color="#FF0000">已通知等待付款</font>';
        }else if($this->IsPay == 2){
        	$strResult .= '</br><font color="#FF0000">已经付款</font>';
        }

        return $strResult;    
	}

	/**
	 * 通过报名ID，发布商品  如果已经存在则修改，如果不存在则添加
	 * @return [type] [description]
	 */
	public static function release($intGoodsBmID){
		if(empty($intGoodsBmID)){
			return false;
		}
		$objModel = self::model()->findByPk($intGoodsBmID);
		if($objModel && $objModel->Status == 1){
			$objGoodsModel = GoodsModel::model()->find(BaseModel::getC(array('GoodsBmID' => $intGoodsBmID, 'order' => 'GoodsID DESC')));			
			if($objGoodsModel){
				$objGoodsModel->setScenario('admin');
			}else{
				$objGoodsModel = new GoodsModel('admin');
			}
			$objGoodsModel->attributes = $objModel->attributes;
			$objGoodsModel->save();
			return $objGoodsModel;
		}else{
			return false;
		}
	}

	/**
	 * 根据前台用户获取其列表
	 * @return [type] [description]
	 */
	public static function getDataUser($UserID = '', $bloIsCache = true){
		empty($UserID) ? $UserID = yii::app()->user->id : '';
		$strKey = "GoodsBmModel_getDataUser" . $UserID;
		$arrCache = yii::app()->cache->get($strKey);
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }

        $arrCache = array();

        $arrCache = self::model()->findAll(BaseModel::getC(array('UserID' => $UserID)));
        //用户所有的报名
/*        foreach ($datas as $key => $data) {
        	$arrCache[$data->GoodsBmID] = $data->attributes;
        }*/

        yii::app()->cache->set($strKey, $arrCache, 1800);
        return $arrCache;	
	}

	public function afterSave(){
		self::getDataUser($this->UserID, false);
		if(CONTROLLER_NAME == 'goodsBm' && ACTION_NAME !== 'release'){
			if($this->Status == 1){
				self::release($this->GoodsBmID);
			}			
		}

	}

	public function afterDelete(){
		self::getDataUser($this->UserID, false);
	}
}
